<template>
    <div class="flow-center">
        <header>
            <div class="left flex items-center">
                <a-button  :icon="h(LeftOutlined)" @click="goBack"/>
                <span class="ml-2">内容</span>
            </div>
            <div class="center">
                <a-steps
                    v-model:current="current"
                    :items="[
                        {
                            title: '基础信息',
                        },
                        {
                            title: '表单设计',
                        },
                        {
                            title: '流程设计',
                        },
                        {
                            title: '更多设置',
                        },
                    ]"
                    >
                </a-steps>
            </div>
            <div class="right">
                <a-button type="dashed" @click="publish">发布</a-button>
            </div>
        </header>
        <div class="content">
            <!-- 基础信息 -->
            <base-info v-show="current == 0" ref="baseInfoRef"></base-info>
            <!-- 表单设计 -->
            <form-design v-show="current == 1" ref="formDesignRef"/>
            <!-- 流程设计 -->
            <logic-flow v-show="current == 2" ref="logicFlowRef"></logic-flow>
            <!-- 更多设置 -->
            <more-setting v-show="current == 3" ref="moreSettingRef"></more-setting>
        </div>
    </div>
</template>

<script setup lang="ts">
import { LeftOutlined } from '@ant-design/icons-vue';
import { h, onBeforeMount, onMounted, ref, useTemplateRef } from 'vue';
import baseInfo from './components/baseInfo/index.vue';
import moreSetting from './components/moreSetting/index.vue'
import logicFlow from './components/logicFlow/index.vue'
import { useRoute, useRouter } from 'vue-router';
import formDesign from './components/formDesign/index.vue'
import { apiGetWfWorkFlowFormData, apiPublish, apiUpdateWfWorkFlowFormData } from '@/api/flow/flow';
import type { ResType } from '@/api/types';
import { getUUID, showMsg } from '@/utils';

const router = useRouter()
const route = useRoute()
const baseInfoRef = useTemplateRef("baseInfoRef")
const logicFlowRef = useTemplateRef('logicFlowRef')
const moreSettingRef = useTemplateRef('moreSettingRef')
const formDesignRef = useTemplateRef('formDesignRef')
const headerH = "50px"
const current = ref<number>(0);

const setLfDataNewId =(lfData:any)=>{
    // 创建节点ID映射表，记录新旧ID对应关系
    const nodeIdMap = new Map<string, string>();
    
    // 先处理节点，生成新ID并建立映射
    lfData.nodes.forEach(node => {
        const oldId = node.id;
        const newId = "node" + getUUID();
        nodeIdMap.set(oldId, newId);
        node.id = newId;
    });
    
    // 处理边，更新ID和引用关系
    lfData.edges.forEach(edge => {
        edge.id = "line" + getUUID();
        
        // 更新源节点ID引用
        if (nodeIdMap.has(edge.sourceNodeId)) {
            edge.sourceNodeId = nodeIdMap.get(edge.sourceNodeId) as string;
        }
        
        // 更新目标节点ID引用
        if (nodeIdMap.has(edge.targetNodeId)) {
            edge.targetNodeId = nodeIdMap.get(edge.targetNodeId) as string;
        }
    });
    
    return lfData;
}

const publish = async()=>{
    const basicInfoData =  await baseInfoRef.value?.getBasicInfoData()
    // await formDesignRef.value?.validateFormSetting()
    const widgets =formDesignRef.value?.getWidgets()
    const lfData = logicFlowRef.value?.getLfData()
    const moreSetting = moreSettingRef.value?.getMoreSetting()
    console.log(basicInfoData,widgets,lfData,moreSetting)
    if(basicInfoData?.id){
        const res = await apiUpdateWfWorkFlowFormData({
            formData:basicInfoData,
            formWidgets:JSON.stringify(widgets),
            flowContent:JSON.stringify(setLfDataNewId(lfData)),
            moreSetting:JSON.stringify(moreSetting)
        }) as ResType<any>
            
        if(res.data.code == 200){
            showMsg("更新成功",'success')
            router.push("/flow/wf")
        }
    }else {
        const res = await apiPublish({
            formData:basicInfoData,
            formWidgets:JSON.stringify(widgets),
            flowContent:JSON.stringify(lfData),
            moreSetting:JSON.stringify(moreSetting)
        }) as ResType<any>
    
        if(res.data.code == 200){
            showMsg("发布成功",'success')
            router.push("/flow/wf")
        }
    }
}
const goBack = ()=>{
    router.go(-1)
}

// 初始化表单和流程数据
const initFormFlowData = async ()=>{
    const formId = route.params.formId
    const res = await apiGetWfWorkFlowFormData(formId) as ResType<any>
    const data = res.data.result
    baseInfoRef.value?.setBasicInfoData(data.formData)
    formDesignRef.value?.setWidgets(JSON.parse(data.formWidgets))
    logicFlowRef.value?.setLfData(JSON.parse(data.flowContent))
    logicFlowRef.value?.setVersionListAndCurVersion(data.versions,data.version)
    moreSettingRef.value?.setMoreSetting(data.moreSetting ? JSON.parse(data.moreSetting) : null)
}

onMounted(()=>{
    if(!route.params.formId) return
    initFormFlowData()
})
</script>

<style lang='scss' scoped>
.flow-center{
    header{
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: v-bind("headerH");
        border-bottom: 1px solid #f0f0f0;
        padding: 0 15px;
        .center{
            width: 50%;
        }
    }
    .content {
        height: calc(100vh - v-bind("headerH"));
        overflow: hidden;
        padding: 15px;
        background-color: #f2f3f5;;
    }
}
</style>